"""Structured logging configuration."""

from __future__ import annotations

import json
import logging
import sys
from datetime import datetime
from typing import Any

from app.core.config import settings


class StructuredFormatter(logging.Formatter):
    """JSON 格式的结构化日志.

    输出格式:
    - 开发环境: 人类可读的 key=value 格式
    - 生产环境: JSON 格式 (便于日志聚合工具解析)
    """

    def __init__(self, use_json: bool = False):
        """初始化格式化器.

        Args:
            use_json: 是否使用 JSON 格式 (生产环境建议 True)
        """
        super().__init__()
        self.use_json = use_json

    def format(self, record: logging.LogRecord) -> str:
        """格式化日志记录."""
        timestamp = datetime.utcnow().isoformat()
        level = record.levelname
        message = record.getMessage()

        log_data = {
            "timestamp": timestamp,
            "level": level,
            "message": message,
            "logger": record.name,
            "module": record.module,
            "function": record.funcName,
            "line": record.lineno,
        }

        # 添加自定义字段
        if hasattr(record, "user_id"):
            log_data["user_id"] = record.user_id

        if hasattr(record, "request_id"):
            log_data["request_id"] = record.request_id

        # 添加异常信息
        if record.exc_info:
            log_data["exception"] = self.formatException(record.exc_info)

        # 根据环境选择输出格式
        if self.use_json:
            return json.dumps(log_data, ensure_ascii=False)
        else:
            # 开发环境: 人类可读格式
            parts = [f"{k}={v}" for k, v in log_data.items() if v]
            return " ".join(parts)


def setup_logging() -> logging.Logger:
    """配置应用日志.

    根据环境自动选择:
    - 开发/测试: 人类可读格式 + DEBUG 级别
    - 生产环境: JSON 格式 + INFO 级别
    """
    logger = logging.getLogger("app")

    # 根据环境设置日志级别
    is_production = settings.ENVIRONMENT == "production"
    logger.setLevel(logging.INFO if is_production else logging.DEBUG)

    # 配置输出到控制台
    handler = logging.StreamHandler(sys.stdout)
    handler.setFormatter(StructuredFormatter(use_json=is_production))
    logger.addHandler(handler)

    # 可选: 配置输出到文件 (生产环境推荐)
    # if is_production:
    #     file_handler = RotatingFileHandler(
    #         "logs/app.log",
    #         maxBytes=10*1024*1024,  # 10MB
    #         backupCount=5
    #     )
    #     file_handler.setFormatter(StructuredFormatter(use_json=True))
    #     logger.addHandler(file_handler)

    return logger


app_logger = setup_logging()


def log_api_call(method: str, path: str, user_id: int | None = None, **kwargs: Any) -> None:
    """Log API call with context."""
    extra = {"user_id": user_id} if user_id else {}
    app_logger.info(f"API {method} {path}", extra=extra, **kwargs)


def log_error(message: str, exc: Exception | None = None, **kwargs: Any) -> None:
    """Log error with exception info."""
    if exc:
        app_logger.error(message, exc_info=exc, **kwargs)
    else:
        app_logger.error(message, **kwargs)
